package com.price.sample.http.interceptor

import android.content.Context
import com.price.httplib.status.NetworkUtil
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response

class HttpCacheInterceptor(private val context: Context): Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request: Request = chain.request()
        // 无网络时，始终使用本地Cache
//        if (!NetworkUtil.isConnected(context)) {
//            request = request.newBuilder()
//                    .cacheControl(CacheControl.FORCE_CACHE)
//                    .build();
//        }
        val response: Response = chain.proceed(request)
        return if (NetworkUtil.isConnected(context)) {
            //有网的时候读接口上的@Headers里的配置，你可以在这里进行统一的设置
            val cacheControl = request.cacheControl.toString()
            response.newBuilder()
                .header("Cache-Control", cacheControl)
                .removeHeader("Pragma")
                .build()
        } else {
            // 无网络时，设置超时为4周
            //            int maxStale = 60 * 60 * 24 * 28;
            //            return response.newBuilder()
            //                    //这里的设置的是我们的没有网络的缓存时间，想设置多少就是多少。
            //                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
            //                    .removeHeader("Pragma")
            //                    .build();
            response
        }
    }
}